package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Slf4j
//easyExcel官方文档 不能将此监听器交给spring管理 所以采取了构造方法传参
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if (data.getOneSubjectName() == null || data.getTwoSubjectName() == null) {
                throw new MyException("excel表格有数据为null");
        }
        if (data != null) {

            EduSubject one = this.one(data.getOneSubjectName());
            if (one == null) {
                one = new EduSubject();
                one.setTitle(data.getOneSubjectName());
                one.setParentId("0");
                eduSubjectService.save(one);
            }
            String pid = one.getId();

            EduSubject two = this.two(data.getTwoSubjectName(), pid);
            if (two == null) {
                two = new EduSubject();
                two.setTitle(data.getTwoSubjectName());
                two.setParentId(pid);
                eduSubjectService.save(two);
            }
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        log.info("所有数据解析完成！");
    }

    //判断一级分类
    private EduSubject one(String oneName) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", oneName).eq("parent_id", 0);
        return eduSubjectService.getOne(wrapper);
    }

    //判断二级分类
    private EduSubject two(String oneName, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", oneName).eq("parent_id", pid);
        return eduSubjectService.getOne(wrapper);
    }
}
